import cryptojs from "crypto-js"
import base64 from "base-64"
let params = {
  "header": {
    "app_id": "e1ddb835",
    "uid": "aef9f963-7"
  },
  "parameter": {
    "chat": {
      "domain": "general",
      "temperature": 0.5,
      "max_tokens": 1024
    }
  },

};

// 去科大讯飞控制台复制-就改改这玩意就差不多了
let temp = {
  APPID: '',
  APISecret: '',
  APIKey: '',
}

function getSocketUrl() {
  var url = "wss://spark-api.xf-yun.com/v1.1/chat";
  var host = "spark-api.xf-yun.com";
  var apiKeyName = "api_key";
  var date = new Date().toGMTString();
  var algorithm = "hmac-sha256";
  var headers = "host date request-line";
  var signatureOrigin = "host: ".concat(host, "\ndate: ").concat(date, "\nGET ").concat('/v1.1/chat', " HTTP/1.1");
  var signatureSha = cryptojs.HmacSHA256(signatureOrigin, temp.APISecret);
  var signature = cryptojs.enc.Base64.stringify(signatureSha);
  var authorizationOrigin = "".concat(apiKeyName, "=\"").concat(temp.APIKey, "\", algorithm=\"").concat(algorithm, "\", headers=\"").concat(headers, "\", signature=\"").concat(signature, "\"");
  var authorization = base64.encode(authorizationOrigin);
  return url = "".concat(url, "?authorization=").concat(authorization, "&date=").concat(encodeURI(date), "&host=").concat(host)
}
let url = null
url = getSocketUrl()
export default class socket {
  obj = null;
  ws = null;
  isConnect = false;
  socketTim = null;
  needReconnect = true;
  constructor(obj) {
    this.obj = obj
    this.initSocket()
  }
  initSocket() {
    if (!url) {
      url = getSocketUrl()
    }
    this.ws = wx.connectSocket({
      url: url,
    })
    this.needReconnect = true
    this.ws.onOpen((e) => {
      console.log(e)
      this.isConnect = true
      this.send(this.obj.data)
    })

    this.ws.onMessage((e) => {
      this.obj.messageCallback(e)
    })

    this.ws.onClose((e) => {
      this.closeSocket(e)
    })

    this.ws.onError((e) => {
      console.log(e, "连接错误")
      // this.reconnectSocket()
    })
  }
  reconnectSocket() {
    if (this.isConnect || !this.needReconnect) return
    if (this.socketTim) clearTimeout(this.socketTim);
    this.socketTim = setTimeout(() => {
      console.log(`%c 🍭 socket重连中`, "color:#ffdd4d");
      // 有延迟 再次判断是否需要重连
      if (!this.isConnect) {
        this.resetSokcet();
        this.initSocket();
      }
    }, 3000);
  }
  resetSokcet() {
    this.ws = null;
    this.isConnect = false;
  }
  closeSocket(e) {
    console.log("%c 🍡 socket连接关闭", "color:#fca650", e);
    this.isConnect = false;
    // this.reconnectSocket()
  }
  send(data) {
    console.log(this.ws.readyState, this.ws)
    if (!this.ws) return
    if (this.ws.readyState === this.ws.OPEN) {
      // 若是ws开启状态
      this.socketSend({
        ...params,
        "payload": {
          "message": {
            "text": data
          }
        }
      });
      // 若是 正在开启状态，则等待1s后重新调用
    } else if (this.ws.readyState === this.ws.CONNECTING) {
      setTimeout(() => {
        this.send(data);
      }, 1000);
    } else {
      // 若未开启 ，则等待1s后重新调用
      setTimeout(() => {
        this.send(data);
      }, 1000);
    }
  }
  socketSend(data) {
    this.ws.send({
      data: JSON.stringify(data)
    });
  }
  close() {
    this.needReconnect = false;
    this.heartCallback = null;
    this.ws && this.ws.close();
    if (this.socketTim) clearTimeout(this.socketTim);
    this.resetSokcet();
  }
}